<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['margin', 'borderbottom', index1 == 0 ? 'bordertop' : '','verticalCenter']"
              v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, index2) in item1.children" :key="item2.id"
                  :class="['padding', index2 == 0 ? '' : 'bordertop','verticalCenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row.children }}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="editRoleMethod(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" @click="setRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%" @closed="resetAddForm">
        <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc" @keyup.enter.native="sendAddRoleRequest"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendAddRoleRequest">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="editRoleVisible" width="50%" @closed="resetEditForm">
        <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleRef" label-width="80px"
          class="demo-ruleForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendEditRoleRequest">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%" @close="closeSetRightsDialog">
        <el-tree :data="rightsList" :props="treeProps" node-key="id" show-checkbox default-expand-all :default-checked-keys="defaultKey" ref="rightsTreeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      // 获取角色列表信息
      rolesList: [],
      // 添加角色对话框开启和关闭
      addRoleVisible: false,
      // 添加角色表单信息
      addRoleForm: {},
      // 添加角色表单验证规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: []
      },
      // 修改角色对话框开启和关闭
      editRoleVisible: false,
      // 修改角色表单信息
      editRoleForm: {},
      // 修改角色表单验证规则
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: []
      },
      // 分配权限对话框
      setRightsDialogVisible: false,
      // 所有权限列表
      rightsList: [],
      // 树形控件属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认勾选的权限
      defaultKey: [],
      // 当前分配权限的角色 id
      roleIdOfSetRight: ''
    }
  },
  methods: {
    async getRolesList () {
      let { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 重置添加角色表单
    resetAddForm () {
      this.$refs.addRoleRef.resetFields()
    },
    // 发送添加角色请求
    async sendAddRoleRequest () {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.addRoleVisible = false
        this.$message.success(res.meta.msg)
        this.getRolesList()
      })
    },
    // 修改角色事件
    async editRoleMethod (id) {
      let { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRoleForm = res.data
      this.editRoleVisible = true
    },
    // 重置修改角色表单
    resetEditForm () {
      this.$refs.editRoleRef.resetFields()
    },
    // 发送修改角色请求
    async sendEditRoleRequest () {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, {
          roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editRoleVisible = false
        this.$message.success('修改成功')
        this.getRolesList()
      })
    },
    // 删除角色
    async deleteRole (id) {
      let confirm = await this.$messageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') return this.$message.info('已取消删除')
      let { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 删除角色指定权限
    async removeRightById (role, rightId) {
      let confirm = await this.$messageBox.confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') return this.$message.info('已取消删除')
      let { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    // 分配权限按钮事件
    async setRights (role) {
      this.roleIdOfSetRight = role.id
      let { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.filterThirdRight(role, this.defaultKey)
      this.setRightsDialogVisible = true
    },
    // 筛选三级权限 id
    filterThirdRight (rights, arr) {
      if (!rights.children) {
        return arr.push(rights.id)
      }
      rights.children.forEach(item => {
        this.filterThirdRight(item, arr)
      })
    },
    // 关闭分配权限对话框
    closeSetRightsDialog () {
      this.defaultKey = []
    },
    // 确定角色授权事件
    async allotRights () {
      let checkedRights = [...this.$refs.rightsTreeRef.getCheckedKeys(), ...this.$refs.rightsTreeRef.getHalfCheckedKeys()]
      let strCR = checkedRights.join(',')
      let { data: res } = await this.$http.post(`roles/${this.roleIdOfSetRight}/rights`, { rids: strCR })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRightsDialogVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 10px;
}
.margin {
  margin: 0 50px;
}

.bordertop {
  border-top: 1px solid #eee;
}

.borderbottom {
  border-bottom: 1px solid #eee;
}

.verticalCenter{
  display: flex;
  align-items: center;
}
</style>
